<!-- 用户信息展示 -->
<!-- 会员购买 -->
<!-- 分享功能 -->

<template>
  <view class="profile-page">
    <!-- 用户信息区域 -->
    <view class="user-info">
      <image class="bg" src="/static/profile-bg.png" mode="aspectFill" />
      <view class="content">
        <view class="avatar-wrap">
          <image class="avatar" :src="userInfo.avatar" mode="aspectFill" />
          <view class="member-tag" v-if="userInfo.isMember">
            <text class="iconfont icon-vip"></text>
            会员
          </view>
        </view>
        <view class="info">
          <text class="nickname">{{ userInfo.nickname }}</text>
          <text class="phone">{{ formatPhone(userInfo.phone) }}</text>
        </view>
        <view class="points">
          <text class="label">我的积分</text>
          <text class="value">{{ userInfo.points }}</text>
        </view>
      </view>
    </view>

    <!-- 会员区域 -->
    <view class="section member-section" v-if="!userInfo.isMember">
      <view class="header">
        <text class="title">开通会员</text>
        <text class="subtitle">解锁全部功能</text>
      </view>
      <view class="member-cards">
        <view
          v-for="item in memberConfig.prices"
          :key="item.type"
          class="member-card"
          :class="{ active: selectedMember === item.type }"
          @click="selectMember(item)"
        >
          <text class="name">{{ item.name }}</text>
          <text class="days">{{ item.days }}天</text>
          <text class="price">¥{{ item.price }}</text>
          <text class="original" v-if="item.original">¥{{ item.original }}</text>
          <text class="tag" v-if="item.tag">{{ item.tag }}</text>
        </view>
      </view>
      <button class="buy-btn" @click="handleBuy">立即开通</button>
    </view>

    <button class="confirm-btn" @click="handlePay">
          立即支付
    </button>

    <!-- 会员权益 -->
    <view class="section">
      <view class="header">
        <text class="title">会员权益</text>
      </view>
      <view class="benefits">
        <view class="benefit-item">
          <text class="iconfont icon-infinity"></text>
          <text>无限次生成题目</text>
        </view>
        <view class="benefit-item">
          <text class="iconfont icon-ad"></text>
          <text>无广告打扰</text>
        </view>
        <view class="benefit-item">
          <text class="iconfont icon-download"></text>
          <text>解锁下载功能</text>
        </view>
      </view>
    </view>

    <!-- 分享奖励 -->
    <view class="section">
      <view class="header">
        <text class="title">分享奖励</text>
        <text class="subtitle">邀请好友得会员</text>
      </view>
      <view class="share-stats">
        <view class="stat-item">
          <text class="value">{{ shareStats.totalInvites }}</text>
          <text class="label">累计邀请</text>
        </view>
        <view class="stat-item">
          <text class="value">{{ shareStats.monthInvites }}</text>
          <text class="label">本月邀请</text>
        </view>
        <view class="stat-item">
          <text class="value">{{ shareStats.totalRewardDays }}</text>
          <text class="label">获得天数</text>
        </view>
        <view class="stat-item">
          <text class="value">{{ shareStats.monthRemainTimes }}</text>
          <text class="label">剩余次数</text>
        </view>
      </view>
      <button class="share-btn" open-type="share">
        <text class="iconfont icon-share"></text>
        分享给好友
      </button>
    </view>

    <!-- 卡密兑换 -->
    <view class="section">
      <view class="header">
        <text class="title">卡密兑换</text>
      </view>
      <view class="exchange-form">
        <input
          type="text"
          v-model="cardNo"
          placeholder="请输入卡密"
          class="input"
        />
        <button class="exchange-btn" @click="handleExchange">
          兑换
        </button>
      </view>
    </view>

    <!-- 支付弹窗 -->
    <uni-popup ref="payPopup" type="bottom">
      <view class="pay-popup">
        <view class="popup-header">
          <text class="title">确认支付</text>
          <button class="close-btn" @click="closePayPopup">
            <text class="iconfont icon-close"></text>
          </button>
        </view>
        <view class="pay-info">
          <view class="item">
            <text class="label">商品名称</text>
            <text class="value">{{ selectedMemberInfo.name }}</text>
          </view>
          <view class="item">
            <text class="label">会员时长</text>
            <text class="value">{{ selectedMemberInfo.days }}天</text>
          </view>
          <view class="item">
            <text class="label">支付金额</text>
            <text class="value price">¥{{ selectedMemberInfo.price }}</text>
          </view>
        </view>
        <view class="pay-method">
          <view class="method-item">
            <view class="left">
              <text class="iconfont icon-wechat"></text>
              <text>微信支付</text>
            </view>
            <text class="iconfont icon-check"></text>
          </view>
        </view>
        <button class="confirm-btn" @click="handlePay">
          立即支付
        </button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import {
  getMemberConfig,
  createOrder,
  getOrderStatus,
  exchangeCard,
  getShareStats
} from '@/api/member'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

// 会员配置
const memberConfig = ref({
  prices: []
})

// 选中的会员类型
const selectedMember = ref(0)
const selectedMemberInfo = computed(() => {
  const found = memberConfig.value.prices.find(item => item.type === selectedMember.value)
  return found || {
    name: '',
    days: 0,
    price: 0
  }
})

// 分享统计
const shareStats = ref({
  totalInvites: 0,
  monthInvites: 0,
  totalRewardDays: 0,
  monthRemainTimes: 10
})

// 卡密兑换
const cardNo = ref('')

// 支付相关
const payPopup = ref(null)
const orderNo = ref('')
const payTimer = ref(null)

// 初始化数据
const initData = async () => {
  try {
    const [configData, statsData] = await Promise.all([
      getMemberConfig(),
      getShareStats()
    ])

    memberConfig.value = configData.member
    shareStats.value = statsData

    // 默认选中第一个会员类型
    if (memberConfig.value.prices.length > 0) {
      selectedMember.value = memberConfig.value.prices[0].type
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  }
}

// 选择会员类型
const selectMember = (item) => {
  selectedMember.value = item.type
}

// 购买会员
const handleBuy = () => {
  if (!selectedMemberInfo.value) return
  payPopup.value.open()
}

// 关闭支付弹窗
const closePayPopup = () => {
  payPopup.value.close()
  clearInterval(payTimer.value)
}

// 发起支付
const handlePay = async () => {
  console.log('handlePay')
  try {
    const { orderNo: no, payParams } = await createOrder({
      type: 1,
      memberType: selectedMember.value
    })

    orderNo.value = no

    // 调起支付
    uni.requestPayment({
      ...payParams,
      success: () => {
        // 支付成功后轮询订单状态
        checkOrderStatus()
      },
      fail: (err) => {
        if (err.errMsg !== 'requestPayment:fail cancel') {
          uni.showToast({
            title: '支付失败',
            icon: 'none'
          })
        }
      }
    })
  } catch (error) {
    uni.showToast({
      title: error.message || '创建订单失败',
      icon: 'none'
    })
  }
}

// 检查订单状态
const checkOrderStatus = () => {
  payTimer.value = setInterval(async () => {
    try {
      const { status } = await getOrderStatus(orderNo.value)
      if (status === 1) {
        clearInterval(payTimer.value)
        closePayPopup()

        // 刷新用户信息
        await userStore.getInfo()

        uni.showToast({
          title: '开通成功',
          icon: 'success'
        })
      }
    } catch (error) {
      clearInterval(payTimer.value)
    }
  }, 1000)
}

// 卡密兑换
const handleExchange = async () => {
  if (!cardNo.value) {
    return uni.showToast({
      title: '请输入卡密',
      icon: 'none'
    })
  }

  try {
    await exchangeCard(cardNo.value)

    // 刷新用户信息
    await userStore.getInfo()

    cardNo.value = ''

    uni.showToast({
      title: '兑换成功',
      icon: 'success'
    })
  } catch (error) {
    uni.showToast({
      title: error.message || '兑换失败',
      icon: 'none'
    })
  }
}

// 工具函数
const formatPhone = (phone) => {
  return phone?.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 分享配置
defineExpose({
  async onShareAppMessage() {
    try {
      const { path, query } = await getShareParams()
      return {
        title: '快来和我一起学习汉字吧',
        path: `${path}?${query}`
      }
    } catch (error) {
      return {
        title: '快来和我一起学习汉字吧',
        path: '/pages/index/index'
      }
    }
  }
})

// 初始化
onMounted(() => {
  initData()
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (payTimer.value) {
    clearInterval(payTimer.value)
  }
})
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: env(safe-area-inset-bottom);
}

.user-info {
  height: 200px;
  position: relative;
  overflow: hidden;

  .bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
  }

  .content {
    position: relative;
    z-index: 2;
    padding: 40px 20px 0;
    color: #fff;
  }

  .avatar-wrap {
    position: relative;
    width: 80px;
    height: 80px;
    margin-bottom: 12px;

    .avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      border: 2px solid #fff;
    }

    .member-tag {
      position: absolute;
      right: -8px;
      bottom: -4px;
      height: 20px;
      padding: 0 8px;
      background: #FFD700;
      border-radius: 10px;
      display: flex;
      align-items: center;
      font-size: 12px;
      color: #fff;

      .iconfont {
        font-size: 14px;
        margin-right: 2px;
      }
    }
  }

  .info {
    .nickname {
      font-size: 20px;
      font-weight: 500;
      margin-bottom: 4px;
      display: block;
    }

    .phone {
      font-size: 14px;
      opacity: 0.8;
    }
  }

  .points {
    position: absolute;
    right: 20px;
    bottom: 20px;
    text-align: right;

    .label {
      font-size: 12px;
      opacity: 0.8;
      display: block;
      margin-bottom: 4px;
    }

    .value {
      font-size: 24px;
      font-weight: 500;
    }
  }
}

.section {
  margin: 16px;
  background: #fff;
  border-radius: 12px;
  padding: 16px;

  .header {
    margin-bottom: 16px;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .subtitle {
      font-size: 12px;
      color: #999;
      margin-left: 8px;
    }
  }
}

.member-section {
  margin-top: -40px;
  position: relative;
  z-index: 3;
}

.member-cards {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;

  .member-card {
    flex: 1;
    height: 120px;
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    padding: 12px;
    position: relative;
    transition: all 0.3s;

    &.active {
      border-color: #2196f3;
      background: rgba(33, 150, 243, 0.05);
    }

    .name {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      display: block;
      margin-bottom: 4px;
    }

    .days {
      font-size: 12px;
      color: #666;
      display: block;
      margin-bottom: 12px;
    }

    .price {
      font-size: 20px;
      color: #f44336;
      font-weight: 500;

      &::before {
        content: '¥';
        font-size: 14px;
      }
    }

    .original {
      font-size: 12px;
      color: #999;
      text-decoration: line-through;
      display: block;
      margin-top: 4px;
    }

    .tag {
      position: absolute;
      top: 0;
      right: 0;
      background: #f44336;
      color: #fff;
      font-size: 12px;
      padding: 2px 6px;
      border-radius: 0 8px 0 8px;
    }
  }
}

.buy-btn {
  width: 100%;
  height: 44px;
  background: linear-gradient(to right, #2196f3, #1976d2);
  border-radius: 22px;
  color: #fff;
  font-size: 16px;
  font-weight: 500;

  &::after {
    display: none;
  }
}

.benefits {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;

  .benefit-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #666;
    font-size: 14px;

    .iconfont {
      font-size: 24px;
      color: #2196f3;
      margin-bottom: 8px;
    }
  }
}

.share-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-bottom: 16px;

  .stat-item {
    text-align: center;

    .value {
      font-size: 20px;
      font-weight: 500;
      color: #333;
      display: block;
      margin-bottom: 4px;
    }

    .label {
      font-size: 12px;
      color: #999;
    }
  }
}

.share-btn {
  width: 100%;
  height: 44px;
  background: rgba(33, 150, 243, 0.1);
  border-radius: 22px;
  color: #2196f3;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;

  &::after {
    display: none;
  }

  .iconfont {
    margin-right: 4px;
  }
}

.exchange-form {
  display: flex;
  gap: 12px;

  .input {
    flex: 1;
    height: 44px;
    background: #f5f7fa;
    border-radius: 8px;
    padding: 0 12px;
    font-size: 14px;
  }

  .exchange-btn {
    width: 80px;
    height: 44px;
    background: #2196f3;
    border-radius: 8px;
    color: #fff;
    font-size: 14px;

    &::after {
      display: none;
    }
  }
}

.pay-popup {
  background: #fff;
  border-radius: 12px 12px 0 0;
  overflow: hidden;

  .popup-header {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    border-bottom: 1px solid #f0f0f0;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .close-btn {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      padding: 0;
      margin: 0;
      line-height: 1;
      color: #999;
      font-size: 20px;

      &::after {
        display: none;
      }
    }
  }

  .pay-info {
    padding: 16px;

    .item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      font-size: 14px;

      .label {
        color: #666;
      }

      .value {
        color: #333;

        &.price {
          color: #f44336;
          font-size: 20px;
          font-weight: 500;
        }
      }
    }
  }

  .pay-method {
    padding: 0 16px;
    margin-bottom: 16px;

    .method-item {
      height: 44px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 12px;
      background: #f5f7fa;
      border-radius: 8px;

      .left {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #333;

        .iconfont {
          font-size: 20px;
          color: #07c160;
          margin-right: 8px;
        }
      }

      .iconfont {
        color: #2196f3;
      }
    }
  }

  .confirm-btn {
    height: 44px;
    background: linear-gradient(to right, #2196f3, #1976d2);
    color: #fff;
    font-size: 16px;
    font-weight: 500;
    border-radius: 0;

    &::after {
      display: none;
    }
  }
}
</style>